package xdu.ble.gateway.filter;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import xdu.ble.common.enums.ExceptionCode;
import xdu.ble.common.exception.BLEException;
import xdu.ble.gateway.config.IgnoreUrlsConfig;
import xdu.ble.gateway.config.JwtProperties;
import xdu.lz.auth.utils.JwtUtils;

import java.util.Objects;


/**
 * 全局身份认证统一处理
 */
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;


    @Autowired
    private JwtProperties properties;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        //防止 OPTIONS 请求直接放行
        if (Objects.equals(request.getMethod(), HttpMethod.OPTIONS)) {
            return chain.filter(exchange);
        }
        //白名单请求直接放行
        if (isAllowPath(request.getURI().getPath())) {
            return chain.filter(exchange);
        }

        // token 验证
        String token = request.getCookies().get(properties.getCookieName()).get(0).getValue();
        log.debug("token = {}", token);
        //4.校验
        try {
            //4.1 校验通过，放行
            JwtUtils.getInfoFromToken(token, properties.getPublicKey());
        } catch (Exception e) {
            //4.2 校验不通过
            log.debug("gateway身份验证不通过,token = {}", token);
            throw new BLEException(ExceptionCode.USER_NOT_LOGIN);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    private boolean isAllowPath(String requestURI) {
        // 遍历允许访问的路径
        for (String path : this.ignoreUrlsConfig.getAllowPaths()) {
            // 然后判断是否是符合
            if (requestURI.startsWith(path)) {
                return true;
            }
        }
        return false;
    }

}
